using System;
using System.Collections.Generic;
using System.Text;

namespace ITDM
{
    static public class Authentication
    {
        public static string AuthenticationHash(string password)
        {
            DateTime d = DateTime.Now;
            string auth_hash = MD5.MD5Sum(password);
            auth_hash = d.Year.ToString() + "-" + d.Month.ToString() + "-" + d.Day.ToString() + "-" + d.Hour.ToString() + "-" + auth_hash;
            auth_hash = MD5.MD5Sum(auth_hash);
            return auth_hash;
        }

        public static void Authenticate(string authentication_hash, string password_hash)
        {
            DateTime now = DateTime.Now;
            bool password_ok = false;
            for (int i = -1; i < 2; i++)
            {
                DateTime d = now.Add(new TimeSpan(i, 0, 0));
                string s = d.Year.ToString() + "-" + d.Month.ToString() + "-" + d.Day.ToString() + "-" + d.Hour.ToString() + "-" + password_hash;
                string md5 = ITDM.MD5.MD5Sum(s);
                if (md5 == authentication_hash)
                    password_ok = password_ok || true;
            }
            if (!password_ok)
                throw new AuthenticationFailedException("Authentication failed. Check password and time syncronization.");
        }

        public class AuthenticationFailedException : Exception
        {
           public AuthenticationFailedException():base(){}

           public AuthenticationFailedException(string message):base(message){}
        }
    }
}
